﻿using System;
using System.Collections.Generic;
using System.Web;

namespace AppBox
{
    public class XDeptHelper
    {
        public static List<MyDept> GetMyDeptCollection(XDeptCollection depts)
        {
            List<MyDept> result = new List<MyDept>();
            ResolveMenuCollection(depts, result, 0, 0);

            return result;
        }

        private static int ResolveMenuCollection(XDeptCollection depts, List<MyDept> result, int parentId, int level)
        {
            // parentId 下面有多少个子节点
            int count = 0;
            foreach (XDept dept in depts)
            {
                if (dept.ParentDeptId == parentId)
                {
                    count++;

                    MyDept my = new MyDept();
                    result.Add(my);
                    my.TreeLevel = level;
                    my.Id = dept.Id;
                    my.Name = dept.Name;
                    my.ParentId = dept.ParentDeptId;
                    my.Remark = dept.Remark;
                    my.SortIndex = dept.SortIndex;

                    level++;
                    // 如果这个节点下没有子节点，则这是个终结节点
                    int childCount = ResolveMenuCollection(depts, result, dept.Id, level);
                    if (childCount == 0)
                    {
                        my.IsTreeLeaf = true;
                    }
                    level--;
                }
            }

            return count;
        }

    }
}
